<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />





  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/0f81ff2f.js","daovoice")
  daovoice('init', {
      app_id: "6d134c3b"
    });
  daovoice('update');
  </script>




















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.4.1" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.4.1">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.4.1">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.4.1">


  <link rel="mask-icon" href="/images/logo.svg?v=6.4.1" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '6.4.1',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="Excel本身提供了非常强大的功能，在数据统计和分析时经常会导出到CSV或者Excel等文件，也常常会从Excel读取数据进行计算。日常的自动化脚本读写数据时我使用比较多的也是Excel。对Excel的操作有各种不同的第三方库，效率以及平台支持都各有千秋。根据综合情况，我选择了支持最多平台，并且语法最简单易用的openpyxl这个库，在此做个简单的使用示例记录，根据每次使用遇到的问题以及解决方法都">
<meta name="keywords" content="Python">
<meta property="og:type" content="article">
<meta property="og:title" content="使用Python提高工作效率之Excel">
<meta property="og:url" content="https://www.lanshiqin.com/983f7127/index.html">
<meta property="og:site_name" content="蓝士钦">
<meta property="og:description" content="Excel本身提供了非常强大的功能，在数据统计和分析时经常会导出到CSV或者Excel等文件，也常常会从Excel读取数据进行计算。日常的自动化脚本读写数据时我使用比较多的也是Excel。对Excel的操作有各种不同的第三方库，效率以及平台支持都各有千秋。根据综合情况，我选择了支持最多平台，并且语法最简单易用的openpyxl这个库，在此做个简单的使用示例记录，根据每次使用遇到的问题以及解决方法都">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://www.lanshiqin.com/983f7127/py_excel_1.png">
<meta property="og:image" content="https://www.lanshiqin.com/983f7127/py_excel_2.png">
<meta property="og:image" content="https://www.lanshiqin.com/983f7127/py_excel_3.png">
<meta property="og:image" content="https://www.lanshiqin.com/983f7127/py_excel_4.png">
<meta property="og:updated_time" content="2019-01-30T11:44:57.570Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="使用Python提高工作效率之Excel">
<meta name="twitter:description" content="Excel本身提供了非常强大的功能，在数据统计和分析时经常会导出到CSV或者Excel等文件，也常常会从Excel读取数据进行计算。日常的自动化脚本读写数据时我使用比较多的也是Excel。对Excel的操作有各种不同的第三方库，效率以及平台支持都各有千秋。根据综合情况，我选择了支持最多平台，并且语法最简单易用的openpyxl这个库，在此做个简单的使用示例记录，根据每次使用遇到的问题以及解决方法都">
<meta name="twitter:image" content="https://www.lanshiqin.com/983f7127/py_excel_1.png">



  <link rel="alternate" href="/atom.xml" title="蓝士钦" type="application/atom+xml" />




  <link rel="canonical" href="https://www.lanshiqin.com/983f7127/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>使用Python提高工作效率之Excel | 蓝士钦</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

  <script src="/js/src/photoswipe.js?v="></script>
  <script src="/js/src/photoswipe-ui-default.js?v="></script>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">蓝士钦</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">编程是一种信仰</p>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-相册">
    <a href="/photos/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-photo"></i> <br />相册</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.lanshiqin.com/983f7127/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="蓝士钦">
      <meta itemprop="description" content="编程是一种信仰">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="蓝士钦">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">使用Python提高工作效率之Excel
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-01-13 11:50:05" itemprop="dateCreated datePublished" datetime="2019-01-13T11:50:05+08:00">2019-01-13</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-01-30 19:44:57" itemprop="dateModified" datetime="2019-01-30T19:44:57+08:00">2019-01-30</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Python/" itemprop="url" rel="index"><span itemprop="name">Python</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon"
            >
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>Excel本身提供了非常强大的功能，在数据统计和分析时经常会导出到CSV或者Excel等文件，也常常会从Excel读取数据进行计算。日常的自动化脚本读写数据时我使用比较多的也是Excel。对Excel的操作有各种不同的第三方库，效率以及平台支持都各有千秋。根据综合情况，我选择了支持最多平台，并且语法最简单易用的<code>openpyxl</code>这个库，在此做个简单的使用示例记录，根据每次使用遇到的问题以及解决方法都会增量修改文章，积累并总结问题能够方便日后遇到相同的问题时能够快速查阅并解决。</p>
<a id="more"></a>
<h1 id="基础部分"><a href="#基础部分" class="headerlink" title="基础部分"></a>基础部分</h1><h2 id="openpyxl支持的Python版本"><a href="#openpyxl支持的Python版本" class="headerlink" title="openpyxl支持的Python版本"></a>openpyxl支持的Python版本</h2><p>python版本必须大于2.7，并且不能是3.0.x到3.3.x的版本。<br><code>openpyxl</code>库不支持.xls后缀的文件只支持.xlsx后缀的Excel文件,不过只要是Office 2007 及后续的版本都支持.xlsx后缀的文件<br>安装<code>openpyxl</code>:<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip install openpyxl</span><br></pre></td></tr></table></figure></p>
<h2 id="openpyxl中API对应的Excel概念"><a href="#openpyxl中API对应的Excel概念" class="headerlink" title="openpyxl中API对应的Excel概念"></a>openpyxl中API对应的Excel概念</h2><ul>
<li>Workbook 工作簿，对应一个.xls或.xlsx后缀的文件</li>
<li>Worksheet 工作表，一个Excel工作簿中，包含一个或多个工作表，通常在Excel的顶部或者底部标签栏中可以看到。</li>
</ul>
<p>首先用Workbook构造或者打开一个Excel文件得到工作簿，然后通过工作簿对象获取Worksheet工作表。<br>通过得到的工作表对象，就可以对该工作表的行和列进行读写操作了。</p>
<h1 id="快速使用"><a href="#快速使用" class="headerlink" title="快速使用"></a>快速使用</h1><h2 id="写入Excel"><a href="#写入Excel" class="headerlink" title="写入Excel"></a>写入Excel</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> datetime</span><br><span class="line"><span class="keyword">from</span> openpyxl <span class="keyword">import</span> Workbook</span><br><span class="line"></span><br><span class="line"><span class="comment"># 创建工作簿</span></span><br><span class="line">wb = Workbook()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 获取激活的工作表（默认为第一个）</span></span><br><span class="line">ws = wb.active</span><br><span class="line"></span><br><span class="line"><span class="comment"># 将当前工作表的A1单元格赋值为42</span></span><br><span class="line">ws[<span class="string">'A1'</span>] = <span class="number">42</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 从有数据单元格的下一行开始，从最左往右单元格分别赋值为 1 2 3</span></span><br><span class="line">ws.append([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>])</span><br><span class="line"></span><br><span class="line"><span class="comment"># 将当前工作表的A2单元格赋值为当前时间</span></span><br><span class="line">ws[<span class="string">'A2'</span>] = datetime.datetime.now()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 从有数据单元格的下一行开始，从最左往右单元格分别赋值为 1 2 3</span></span><br><span class="line">ws.append([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>])</span><br><span class="line"></span><br><span class="line"><span class="comment"># 将文件内容保存到当前目录的 sample.xlsx 文件中</span></span><br><span class="line">wb.save(<span class="string">"sample.xlsx"</span>)</span><br></pre></td></tr></table></figure>
<p>上述代码中<code>ws[&#39;A2&#39;]</code>将A2原本的值<code>1</code>修改成了当前时间。<br>保存后的Excel工作簿打开如下所示<br><img src="/983f7127/py_excel_1.png" title="py_excel_1"></p>
<h2 id="读取Excel"><a href="#读取Excel" class="headerlink" title="读取Excel"></a>读取Excel</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> openpyxl <span class="keyword">import</span> load_workbook</span><br><span class="line"></span><br><span class="line"><span class="comment"># 加载工作簿</span></span><br><span class="line">wb = load_workbook(filename=<span class="string">'sample.xlsx'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 获取激活的工作表</span></span><br><span class="line">ws = wb.active</span><br><span class="line"></span><br><span class="line"><span class="comment"># 打印工作表A1单元格的值</span></span><br><span class="line">print(ws[<span class="string">'A1'</span>].value)</span><br></pre></td></tr></table></figure>
<h1 id="复杂一点的用法"><a href="#复杂一点的用法" class="headerlink" title="复杂一点的用法"></a>复杂一点的用法</h1><h2 id="写入Excel文件"><a href="#写入Excel文件" class="headerlink" title="写入Excel文件"></a>写入Excel文件</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> openpyxl <span class="keyword">import</span> Workbook</span><br><span class="line"><span class="keyword">from</span> openpyxl.styles <span class="keyword">import</span> Font</span><br><span class="line"><span class="keyword">from</span> openpyxl.styles <span class="keyword">import</span> colors</span><br><span class="line"><span class="keyword">from</span> openpyxl.styles <span class="keyword">import</span> Alignment</span><br><span class="line"></span><br><span class="line"><span class="comment"># 创建工作簿</span></span><br><span class="line">wb = Workbook()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 获取激活的工作表（默认名称为Sheet）</span></span><br><span class="line">ws = wb.active</span><br><span class="line"></span><br><span class="line"><span class="comment"># 设置工作表名称</span></span><br><span class="line">ws.title = <span class="string">"99乘法表"</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> x <span class="keyword">in</span> range(<span class="number">1</span>, <span class="number">10</span>):</span><br><span class="line">    <span class="keyword">for</span> y <span class="keyword">in</span> range(<span class="number">1</span>, <span class="number">10</span>):</span><br><span class="line">        <span class="keyword">if</span> x &gt;= y:</span><br><span class="line">            ws.cell(x, y, str(y) + <span class="string">"*"</span> + str(x) + <span class="string">"="</span> + str(x * y))</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">continue</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 创建 "教师信息" 工作表，工作表位置为默认值</span></span><br><span class="line">ws_teacher = wb.create_sheet(<span class="string">"教师信息"</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 创建 "学生信息" 工作表,并设置工作表位置为第1个</span></span><br><span class="line">ws_student = wb.create_sheet(<span class="string">"学生信息"</span>, <span class="number">1</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 设置 "学生信息" 工作表的标签颜色，该值为RGB值</span></span><br><span class="line">ws_student.sheet_properties.tabColor = <span class="string">"1072BA"</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 将"学生信息" 工作表的第1行第1列赋值为"姓名"</span></span><br><span class="line">ws_student.cell(row=<span class="number">1</span>, column=<span class="number">1</span>, value=<span class="string">"姓名"</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 将"学生信息" 工作表的第2行第1列赋值为"蓝士钦"</span></span><br><span class="line">ws_student.cell(row=<span class="number">2</span>, column=<span class="number">1</span>, value=<span class="string">"蓝士钦"</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 合并A1到F1单元格</span></span><br><span class="line">cell = ws_teacher.merge_cells(<span class="string">'A1:F1'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 设置单元格字体为蓝色，15号大小，斜体</span></span><br><span class="line">ws_teacher[<span class="string">'A1'</span>].font = Font(color=colors.BLUE, size=<span class="number">15</span>, italic=<span class="keyword">True</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 设置为垂直居中对齐,水平居中对齐</span></span><br><span class="line">ws_teacher[<span class="string">'A1'</span>].alignment = Alignment(vertical=<span class="string">'center'</span>, horizontal=<span class="string">'center'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 为单元格赋值</span></span><br><span class="line">ws_teacher[<span class="string">'A1'</span>] = <span class="string">"教师信息标题"</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 将"教师信息" 工作表的第6行第6列赋值为"测试"</span></span><br><span class="line">ws_teacher.cell(row=<span class="number">6</span>, column=<span class="number">6</span>, value=<span class="string">"测试"</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 从 "学生信息" 工作表拷贝到新工作表</span></span><br><span class="line">target = wb.copy_worksheet(ws_student)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 设置工作表的名称</span></span><br><span class="line">target.title = <span class="string">"新工作表"</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 将文件内容保存到当前目录的 sample2.xlsx 文件中</span></span><br><span class="line">wb.save(<span class="string">"sample2.xlsx"</span>)</span><br></pre></td></tr></table></figure>
<p>保存后的Excel工作簿打开，对应有多个工作表，每个工作表的内容分别如下所示：<br><img src="/983f7127/py_excel_2.png" title="py_excel_2"><br><img src="/983f7127/py_excel_3.png" title="py_excel_3"><br><img src="/983f7127/py_excel_4.png" title="py_excel_4"></p>

<h2 id="读取Excel文件"><a href="#读取Excel文件" class="headerlink" title="读取Excel文件"></a>读取Excel文件</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> openpyxl <span class="keyword">import</span> load_workbook</span><br><span class="line"></span><br><span class="line"><span class="comment"># 加载工作簿</span></span><br><span class="line">wb = load_workbook(filename=<span class="string">'sample2.xlsx'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 获取所有工作表</span></span><br><span class="line">wss = wb.worksheets</span><br><span class="line"></span><br><span class="line"><span class="comment"># 遍历工作表</span></span><br><span class="line"><span class="keyword">for</span> ws <span class="keyword">in</span> wss:</span><br><span class="line">    <span class="comment"># 打印指定工作表的所有单元格的值</span></span><br><span class="line">    <span class="keyword">if</span> ws.title == <span class="string">"99乘法表"</span>:</span><br><span class="line">        <span class="keyword">for</span> row <span class="keyword">in</span> ws.rows:</span><br><span class="line">            <span class="keyword">for</span> index <span class="keyword">in</span> row:</span><br><span class="line">                <span class="keyword">if</span> index.value <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">                    <span class="keyword">continue</span></span><br><span class="line">                <span class="keyword">else</span>:</span><br><span class="line">                    print(index.value + <span class="string">'\t'</span>, end=<span class="string">''</span>)</span><br><span class="line">            print(<span class="string">''</span>)</span><br><span class="line">            <span class="keyword">continue</span></span><br></pre></td></tr></table></figure>
<p>有关openpyxl操作Excel单元格的样式和更详细的用法，参考其他作者的文章：<br><a href="https://www.jianshu.com/p/7af9a7c5b27d" target="_blank" rel="noopener">https://www.jianshu.com/p/7af9a7c5b27d</a></p>
<p>openpyxl官方文档地址：<br><a href="https://openpyxl.readthedocs.io/en/stable/" target="_blank" rel="noopener">https://openpyxl.readthedocs.io/en/stable/</a></p>

      
    </div>

    

    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"><i class="fa fa-tag"></i> Python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/b4dc6b2c/index.html" rel="next" title="使用Python提高工作效率之MySQL">
                <i class="fa fa-chevron-left"></i> 使用Python提高工作效率之MySQL
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/204682e6/index.html" rel="prev" title="使用Python提高工作效率之SQLite">
                使用Python提高工作效率之SQLite <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div id="gitalk-container"></div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.png"
                alt="蓝士钦" />
            
              <p class="site-author-name" itemprop="name">蓝士钦</p>
              <p class="site-description motion-element" itemprop="description">编程是一种信仰</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">36</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">7</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">12</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/lanshiqin" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://weibo.com/l18120788756" target="_blank" title="Weibo"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.jianshu.com/u/082f73dac819" target="_blank" title="JianShu"><i class="fa fa-fw fa-heartbeat"></i>JianShu</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:lanshiqin@outlook.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#基础部分"><span class="nav-number">1.</span> <span class="nav-text">基础部分</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#openpyxl支持的Python版本"><span class="nav-number">1.1.</span> <span class="nav-text">openpyxl支持的Python版本</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#openpyxl中API对应的Excel概念"><span class="nav-number">1.2.</span> <span class="nav-text">openpyxl中API对应的Excel概念</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#快速使用"><span class="nav-number">2.</span> <span class="nav-text">快速使用</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#写入Excel"><span class="nav-number">2.1.</span> <span class="nav-text">写入Excel</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#读取Excel"><span class="nav-number">2.2.</span> <span class="nav-text">读取Excel</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#复杂一点的用法"><span class="nav-number">3.</span> <span class="nav-text">复杂一点的用法</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#写入Excel文件"><span class="nav-number">3.1.</span> <span class="nav-text">写入Excel文件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#读取Excel文件"><span class="nav-number">3.2.</span> <span class="nav-text">读取Excel文件</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">蓝士钦</span>

  

  
</div>










  <div class="footer-custom">闽ICP备15027850号</div>


        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    
	
    

    
  </div>

  

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.4.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.4.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.1"></script>
<script src="/js/src/photoswipe.js?v="></script>
<script src="/js/src/photoswipe-ui-default.js?v="></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.1"></script>



  



  










  <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">
  <script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>
   <script type="text/javascript">
        var gitalk = new Gitalk({
          clientID: '08543e172f1359fce9c3',
          clientSecret: 'a8dd355f95e5035e0266c695e489fa991c9d28e2',
          repo: 'lanshiqin-blog',
          owner: 'lanshiqin',
          admin: ['lanshiqin'],
          id: location.pathname,
          distractionFreeMode: 'true'
        })
        gitalk.render('gitalk-container')           
       </script>

  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  

  

</body>
</html>
<!-- 页面点击小红心 --> 
<script type="text/javascript" src="/js/src/love.js"></script>
<!--崩溃欺骗-->
<script type="text/javascript" src="/js/src/crash_cheat.js"></script>